import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'models/detail_list.dart';
import 'component.dart';
import 'utils/date_tool.dart';

const Color tableBorderColor = Color(0xFF202836);
const horizontalHeadHeight = 35.0;
const horizontalHeadWidth = 95.0;
const vorticalHeadWidth = 100.0;

const columns = [
  '存款差额',
  '存款总额',
  '提款总额',
  '存款人数',
  '注册人数',
  '首存人数',
  '提款人数',
  '首存总额',
  '次存人数',
  '次存总额',
  '快入人数',
  '在支人数',
  'PC人数',
  'H5人数',
  'App人数',
  '注单人数',
  '有效投注',
  '派彩输赢',
  '新客存款总额',
  '新客提款总额',
  '新客有效投注额',
  '新客人数'
];

class _AllDetailTableState extends State<AllDetailTable> {
  ScrollController hHeaderController =
      ScrollController(keepScrollOffset: false);
  ScrollController vHeaderController =
      ScrollController(keepScrollOffset: false);
  ScrollController hTableController = ScrollController(keepScrollOffset: false);
  ScrollController vTableController = ScrollController(keepScrollOffset: false);
  int currentIndex = 1;

  @override
  void initState() {
    hTableController.addListener(() {
      hHeaderController.jumpTo(hTableController.offset);
    });
    vTableController.addListener(() {
      vHeaderController.jumpTo(vTableController.offset);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          height: horizontalHeadHeight,
          child: Row(
            children: <Widget>[
              GestureDetector(
                child: Container(
                  decoration: BoxDecoration(
                      border: Border.all(
                          width: 1,
                          style: BorderStyle.solid,
                          color: tableBorderColor)),
                  child: Center(
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          widget.filterItems[currentIndex],
                          style: TextStyle(color: Color(0xFF758BB5)),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Image(
                          image: AssetImage('images/arrow_down.png'),
                          width: 10,
                        )
                      ],
                    ),
                  ),
                  width: vorticalHeadWidth,
                ),
                onTap: () {
                  changeDateType();
                },
              ),
              Expanded(
                child: Container(
                    height: horizontalHeadHeight,
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      physics: NeverScrollableScrollPhysics(),
                      controller: hHeaderController,
                      child: makeHorizontalHead(),
                    )),
              )
            ],
          ),
        ),
        Expanded(
          child: Container(color: Colors.black,
              child:Row(
                crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: vorticalHeadWidth,
                child: SingleChildScrollView(
                    physics: ClampingScrollPhysics(
                        parent: NeverScrollableScrollPhysics()),
                    controller: vHeaderController,
                    child: makeVerticalTableHead()),
              ),
              Expanded(
                child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    controller: hTableController,
                    physics: ClampingScrollPhysics(),
                    child: SingleChildScrollView(
                        physics: ClampingScrollPhysics(),
                        controller: vTableController,
                        child: Container(child: makeTable(),)
                    )
                ),
              )
            ],
          )),
        )
      ],
    );
  }

  Table makeHorizontalHead() {
    if (widget.datas == null ||
        widget.datas.resObj == null ||
        widget.datas.resObj.length == 0) {
      return null;
    }
    Map<int, TableColumnWidth> widthInfo = {};
    for (int i = 0; i < widget.datas.resObj.length; i++) {
      widthInfo[i] = FixedColumnWidth(horizontalHeadWidth);
    }
    return Table(
        border: TableBorder.all(color: tableBorderColor, width: 1),
        columnWidths: widthInfo,
        children: [
          TableRow(
              children: widget.datas.resObj.map((e) {
            return TableCell(
                child: Container(
              height: horizontalHeadHeight,
              child: Center(
                child: Text(
                  e.domain,
                  style: TextStyle(color: Color(0xFF758BB5)),
                ),
              ),
            ));
          }).toList())
        ]);
  }

  Widget makeVerticalTableHead() {
    return Table(
        border: TableBorder.all(color: tableBorderColor, width: 1),
        children: widget.indexes.map((e) {
          return TableRow(children: [
            TableCell(
              child: Container(
                color: Colors.black,
                  height: 25,
                  child: Center(
                    child: Text(
                      e,
                      maxLines: 1,
                      style: TextStyle(color: Color(0xFF758BB5)),
                    ),
                  )),
            )
          ]);
        }).toList());
  }

  Map<String, String> makeInfoMap(DetailListEntity entity) {
    return {
      '存款差额': entity.profitAmount,
      '存款总额': entity.totalDepositAmount,
      '提款总额': entity.totalAtmAmount,
      '存款人数': entity.totalDepositCount,
      '注册人数': entity.totalRegistCount,
      '首存人数': entity.depositFirstCount,
      '提款人数': entity.atmCount,
      '首存总额': entity.depositFirstAmount,
      '次存人数': entity.depositSecondCount,
      '次存总额': entity.depositSecondAmount,
      '快入人数': entity.depositQuickCount,
      '在支人数': entity.depositOnlineCount,
      'PC人数': entity.depositPcCount,
      'H5人数': entity.depositWapCount,
      'App人数': entity.depositAppCount,
      '注单人数': entity.betCount,
      '有效投注': entity.betValidAmount,
      '派彩输赢': entity.betPayoutAmount,
      '新客存款总额':entity.newClientTotalDeposit,
      '新客提款总额':entity.newClientTotalAtm,
      '新客有效投注额':entity.newClientBetValidAmount,
      '新客人数': entity.newClientCount
    };
  }

  List<List<String>> normalizeData() {
    const items = [
      '存款差额',
      '存款总额',
      '提款总额',
      '存款人数',
      '注册人数',
      '首存人数',
      '提款人数',
      '首存总额',
      '次存人数',
      '次存总额',
      '快入人数',
      '在支人数',
      'PC人数',
      'H5人数',
      'App人数',
      '注单人数',
      '有效投注',
      '派彩输赢',
      '新客存款总额',
      '新客提款总额',
      '新客有效投注额',
      '新客人数'
    ];
    List<List<String>> allInfos = List<List<String>>();
    for (int j = 0; j < items.length; j++) {
      final currentItem = items[j];
      List<String> cacheInfo = [];
      for (int i = 0; i < widget.datas.resObj.length; i++) {
        final entity = widget.datas.resObj[i];
        cacheInfo.add(makeInfoMap(entity)[currentItem]);
      }
      allInfos.add(cacheInfo);
    }
    return allInfos;
  }

  Widget makeTable() {
    if (widget.isLoad) {
      return LoadingBlock();
    }
    if (widget.hasError) {
      return Container(
        width: 550,
        //color: Color.fromRGBO(255, 255, 255, 1),
          child: ErrorBlock(
        errorType: ErrorType.noNetwork,
      ));
    }
    if (widget.datas == null || widget.datas.resObj == null || widget.datas.resObj.length == 0) {
      return Container(
        color: Colors.black,
        width: 550,
          height: 450,
          child: ErrorBlock(
            errorType: ErrorType.noData,
          ));
    }
    Map<int, TableColumnWidth> widthInfo = {};
    for (int i = 0; i < widget.datas.resObj.length; i++) {
      widthInfo[i] = FixedColumnWidth(horizontalHeadWidth);
    }
    final normalList = normalizeData();
    return Table(
        border: TableBorder.all(color: tableBorderColor, width: 1),
        columnWidths: widthInfo,
        children: normalList.map((e) {
          return TableRow(
              children: e.map((ie) {
            return TableCell(
                child: Container(
                  color: Colors.black,
              height: 25,
              child: Center(
                child: Text(
                  ie,
                  style: TextStyle(color: Color(0xFF758BB5)),
                ),
              ),
            ));
          }).toList());
        }).toList());
  }

  Future<void> changeDateType() async {
    int i = await showDialog<int>(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
              title: const Text('日期类型'),
              children: widget.filterItems.map((e) {
                var curIdx = widget.filterItems.indexOf(e);
                return SimpleDialogOption(
                  onPressed: () {
                      Navigator.pop(context, curIdx);
                  },
                  child: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 6),
                    child: Text(e),
                  ),
                );
              }).toList());
        });

    if (i != null) {
      setState(() {
        currentIndex = i;
        if(i != 0) {
          widget.onClick(i);
        } else {
          _chooseStartDate(context);
        }
      });
    }
  }

  Future<void> _chooseStartDate(BuildContext context) async{
    DateTime date_start = await showDatePicker(context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(1990),
        lastDate: DateTime.now(),
        builder: (BuildContext context, widget) {
          return Stack(
            children: <Widget>[
              widget,
              Positioned(
                child: Text('开始日期', style: TextStyle(color: Colors.white, fontSize: 15, decoration: null)),
                bottom: 100,
                left: 100,
              )
            ],
          );
        });
    if(date_start == null) {
      return;
    }
    DateTime date_end = await showDatePicker(context: context,
        initialDate: date_start,
        firstDate: date_start,
        lastDate: DateTime.now(),
        builder: (BuildContext context, widget) {
          return Stack(
            children: <Widget>[
              widget,
              Positioned(
                child: Text('结束日期', style: TextStyle(color: Colors.white, fontSize: 15, decoration: null)),
                bottom: 100,
                left: 100,
              )
            ],
          );
        });
    if(date_end != null && date_start != null) {
      widget.onDateChoose(DateTool.toNormalDateStr(date_start), DateTool.toNormalDateStr(date_end));
    }
  }

  @override
  void dispose() {
    vHeaderController.dispose();
    hHeaderController.dispose();
    vTableController.dispose();
    hTableController.dispose();
    super.dispose();
  }
}

class AllDetailTable extends StatefulWidget {
  const AllDetailTable(
      {Key key,
        this.filterItems = const ['自定义','实时', '昨日', '前日', '本周', '上周', '本月', '上月', '上上月'],
      this.indexes = columns,
      @required this.datas,
      @required this.onClick,
        this.onDateChoose,
      this.hasError,
      this.isLoad})
      : super(key: key);
  final List<String> filterItems;
  final List<String> indexes;
  final DetailListModel datas;
  final void Function(int) onClick;
  final void Function(String, String) onDateChoose;
  final bool isLoad;
  final bool hasError;

  @override
  _AllDetailTableState createState() {
    return _AllDetailTableState();
  }
}
